<?php

namespace app\admin\controller\expert;

use app\admin\model\User;
use app\common\controller\Backend;
use Exception;
use fast\Tree;
use think\Cache;
use think\Db;
use think\Log;

/**
 *  三星达人加权分红明细管理
 *
 * @icon   fa fa-list
 * @remark 
 */
class ExpertWeightingScoreDetail extends Backend
{

    protected $searchFields = 'u.mobile';

    protected $level = "1";
    protected $type = "1";

    public function _initialize()
    {
        parent::_initialize();

        //月份列表
        $month = input("month", "");
        $monthList = $this->_monthList();
        $this->view->assign('monthList', build_select('row[monthList]', $monthList, $month, ['class' => 'form-control month-list']));
        $this->assignconfig('monthList', $monthList);
        $this->assignconfig('month', $month);

        //级别
        $this->assign("level", $this->level);
    }


    /**
     * 月份列表
     */
    private function _monthList()
    {
        $re[""] = "请选择月份";
        $StartMonth   = date('Y-m', strtotime('-6 Month')); //开始日期
        $EndMonth     = date('Y-m', strtotime('+1 Month', time())); //结束日期
        $ToStartMonth = strtotime($StartMonth); //转换一下
        $ToEndMonth   = strtotime($EndMonth); //一样转换一下
        $i            = false; //开始标示
        while ($ToStartMonth < $ToEndMonth) {
            $NewMonth = !$i ? date('Y-m', strtotime('+0 Month', $ToStartMonth)) : date('Y-m', strtotime('+1 Month', $ToStartMonth));
            $ToStartMonth = strtotime($NewMonth);
            $i = true;
            $key = date("Ym", strtotime($NewMonth . "-01 00:00:00"));
            $re[$key] = $NewMonth;
        }
        return $re;
        // exit(print_r($re));
    }

    /**
     * 列表
     */
    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }

            $filter = json_decode($this->request->get("filter", ''), true);
            $op = json_decode($this->request->get("op", '', 'trim'), true);

            //默认加入的查询条件

            $filter["uwsd.type"] = 1;
            $op["uwsd.type"] = "=";

            $this->request->get(['filter' => json_encode($filter, true)]);
            $this->request->get(['op' => json_encode($op, true)]);

            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $list_info = db("user_weighting_score_detail uwsd")
                ->join('user u', "uwsd.user_id=u.id", "LEFT")
                ->field("uwsd.*,u.nickname,u.avatar,u.mobile")
                ->where($where)
                ->order($sort, $order)
                ->paginate($limit);

            // exit(db()->getLastSql());

            $list = $list_info->items();
            $total = $list_info->total();

            foreach ($list as $k => $v) {
                // exit(print_r($v));

                $list[$k]["avatar"] = $v["avatar"] ? cdnurl($v["avatar"], true) : letter_avatar($v["nickname"]);
                unset($list[$k]["password"]);
                unset($list[$k]["salt"]);
            }
            $result = array("total" => $total, "rows" => $list);
            return json($result);
        }

        return $this->view->fetch();
    }

    /**
     * 开始分红
     */
    public function start_score()
    {
        $month = input("month");

        $month_config = db("user_weighting_month_config")->where("type", 1)->where("month",  $month)->find();
        if ($month_config) {
            $this->error("本月已分红过一次");
        }

        $list = db("user_weighting_score_detail")->where("type", 1)->where("status", 0)->where("month", $month)->select();
        $total = 0;
        if ($list) {
            foreach ($list as $detail) {
                $money = $detail['money'];
                Db::transaction(function () use ($detail, $money,&$total) {
                //查询积分记录表
                $user_score = Db::name("user")->where("id", $detail["user_id"])->value("h5_score");
                $unissued_money = $user_score > $money ?0:($money-$user_score);
                $money =  $user_score > $money ? $money : $user_score;
                //扣减积分
                Db::name("mini_user_score_log")->insert([
                    "user_id" => $detail["user_id"],
                    "score" => $money,
                    "before" => $user_score,
                    "after" => $user_score - $money,
                    "remark" => "等级分红扣减",
                    "link_id" => $detail["id"],
                    "link_table" => "fa_user_weighting_score_detail",
                    "type" => 3,
                    "from" => 2,
                    "create_time" => time(),
                ]);
                Db::name("user")->where("id", $detail["user_id"])->setDec("h5_score", $money);



                    Db::name("user_weighting_score_detail")->where("id", $detail["id"])->update([
                    "status" => 1,
                    "pay_money" => $money,//更新实际到账
                    "update_time" => time(),
                ]);

                    $h5_money = Db::name("user")->where("id", $detail["user_id"])->value("h5_money");

                Db::name("mini_user_money_log")->insert([
                    "user_id" => $detail["user_id"],
                    "money" => $money,
                    "before" => $h5_money,
                    "after" => $h5_money + $money,
                    "remark" => "等级分红",
                    "link_id" => $detail["id"],
                    "link_table" => "fa_user_weighting_score_detail",
                    "type" => 6,
                    "from" => 1,
                    "create_time" => time(),
                ]);
                    //改成累计实际到账的
                    Db::name("user")->where("id", $detail["user_id"])->setInc("all_profit", $money);
                    Db::name("user")->where("id", $detail["user_id"])->setInc("h5_money", $money);
                    Db::name("user")->where("id", $detail["user_id"])->setInc("unissued_money", $unissued_money);
                    $total= $total+$money;
                });
            }
            // exit(print_r($list));

            //添加到每月配置表
            db("user_weighting_month_config")->insert(["type" => 1,"status" => 2, "month" =>  $month,'total'=>$total, "addtime" => time()]);

            $this->success("分红已完成");
        } else {
            $this->error("没有分红的人员列表");
        }
    }


    /**
     * 生成记录
     */
//    public function create_record()
//    {
//        $month = input("month");
//        $total_score = input("total_score");
//        $task = Db::name("job_task")->where(["type"=>1,'month'=>$month])->find();
//        if (!empty($task) && $task['status'] ==2) {
//            $this->error("发放记录生成中，请完成后再操作！");
//        }
//        Db::transaction(function () use ($month) {
//            //删除任务
//            Db::name("job_task")->where(["type"=>1,'month'=>$month])->delete();
//            //删除记录
//            Db::name("user_weighting_score_detail")->where(["type"=>1,'month'=>$month])->delete();
//        });
//
//
//        $data = [
//            'month' => $month,
//            'total_money' => trim($total_score),
//            'status' => 0,
//            'type' => 1,
//            'add_time' => time(),
//            'last_id' => 0,
//        ];
//        $lastId = Db::name("job_task")->insertGetId($data);
//        if ($lastId) {
//            $data = [];
//            $data['logId'] = $lastId; //任务订单id
//            \think\Queue::push('\app\common\library\job\ReleaseIncomeJob@createLog', $data, 'ReleaseIncome');
//        }
//        $this->success("本月已红任务已生成！请完成生成任务后点击【执行分红】按钮分红");
//    }

    public function create_record()
    {

        $month = input("month");
        $total_score = input("total_score");
        $task = Db::name("job_task")->where(["type"=>1,'month'=>$month])->find();
        if (!empty($task) && $task['status'] ==2) {
//            $this->error("发放记录生成中，请完成后再操作！");
        }
        $month_config = db("user_weighting_month_config")->where("type",1)->where("month", $month)->find();
        if ($month_config && $month_config['status']==2) {
            $this->error("本月已分红过", "", $month_config);
        }

        Db::transaction(function () use ($month) {
            //删除任务
            Db::name("job_task")->where(["type"=>1,'month'=>$month])->delete();
            //删除记录
            Db::name("user_weighting_score_detail")->where(["type"=>1,'month'=>$month])->delete();
        });

        $data = [
            'month' => $month,
            'total_money' => trim($total_score),
            'status' => 0,
            'type' => 1,
            'add_time' => time(),
            'last_id' => 0,
        ];
        $lastId = Db::name("job_task")->insertGetId($data);
        $taskId = $lastId;
        $task = Db::name("job_task")->where("id", $taskId)->find();
        if(empty($task) || $task['status'] !=0){
            $this->error("发放记录生成中，请完成后再操作！");
        }

        $DiLevelMoney= User::DiLevelMoney($task['total_money']);
//        var_dump($DiLevelMoney);die;
        $page = 1;
        $time = time();
        $lastId = $task['last_id'];
        do{
            $list = Db::name("user")->whereIn("user_level", [1,2,3,4,5,6])->order('id ASC')->page($page,50)->select();
            $dataSet = [];
            foreach ($list as $user) {
                //处理记录
                $lastId = $user['id'];
                $temp = [];
                $temp['user_id'] = $user['id'];
                $temp['level'] = $user['user_level'];
                $temp['type'] = 1;
                $temp['money'] = floor($DiLevelMoney[$user['user_level']]['totalMoney']);
                $temp['level_money'] = $DiLevelMoney[$user['user_level']]['money'];
                $temp['add_time'] = $time;
                $temp['status'] = 0;
                $temp['month'] = $task['month'];
                $temp['jsondata'] = json_encode($DiLevelMoney);
                $dataSet[] = $temp;
            }
            Db::transaction(function () use ($taskId, $dataSet,$lastId) {
                 Db::name('user_weighting_score_detail')->insertAll($dataSet);
                 Db::name('job_task')->where(['id'=>$taskId])->update(['update_time'=>time(),'last_id'=>$lastId,'status'=>2]);
            });
            $page++;
        }while(!empty($list));
        Db::name('job_task')->where(['id'=>$taskId])->update(['update_time'=>time(),'last_id'=>$lastId,'status'=>2]);
        $this->success("本月已红任务已生成！请完成生成任务后点击【执行分红】按钮分红");
    }

    /**
     * 查询当月分红情况
     */
    public function query_month_score()
    {
        $month = input("month");
        $month_config = db("user_weighting_month_config")->where("type",1)->where("month", $month)->find();
        $date = empty($month) ? date("Ym01",time()):$month.'01';

        $firstDate =date("Ym01 00:00:00",strtotime($date));
        $lastDate =date("Ymd 23:59:59",strtotime("$firstDate +1 month -1 day"));
        $firstDate =strtotime($firstDate);
        $lastDate =strtotime($lastDate);
//        var_dump($firstDate,$lastDate);
        $totalMoney = Db::name("wechat_orders")->where('status',1)->whereBetween('order_createtime',[$firstDate,$lastDate])->sum('order_price');
        $totalMoney = $totalMoney/100;

        if ($month_config) {
            $month_config['total_money'] = $totalMoney;
            $month_config['percentage_money'] = round($totalMoney * 0.05,2);
            $this->success("本月已分红过", "", $month_config);
        } else {
            $this->error("本月未分红过", "", ["month" => $month,'total_money'=>$totalMoney,'percentage_money'=>round($totalMoney * 0.05,2)]);
        }
    }
}
